#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CodeBuddy登录测试脚本
用于测试提供的fetch请求是否能成功登录到CodeBuddy认证系统
"""

import requests
from urllib.parse import unquote
import json
import time
from bs4 import BeautifulSoup

class CodeBuddyLogin:
    def __init__(self):
        self.session = requests.Session()
        self.base_url = "https://www.codebuddy.ai"
        
    def setup_headers(self):
        """设置通用请求头"""
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36 Edg/139.0.0.0",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "sec-ch-ua": "\"Not;A=Brand\";v=\"99\", \"Microsoft Edge\";v=\"139\", \"Chromium\";v=\"139\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
        })
    
    def get_login_page(self):
        """获取登录页面，建立初始session"""
        print("📄 正在获取登录页面...")
        
        try:
            # 访问主页面，可能会重定向到登录页
            response = self.session.get(f"{self.base_url}/console", allow_redirects=True)
            print(f"✅ 登录页面状态码: {response.status_code}")
            print(f"🔗 当前URL: {response.url}")
            
            # 检查是否已经重定向到认证页面
            if "auth/realms" in response.url:
                print("🔐 已重定向到认证页面")
                return True
            else:
                print("⚠️ 未重定向到认证页面，可能已登录或需要其他步骤")
                return False
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 获取登录页面失败: {e}")
            return False
    
    def attempt_direct_login(self):
        """使用提供的fetch请求参数直接尝试登录"""
        print("\n🚀 开始尝试直接登录...")
        
        # 登录URL（来自提供的fetch请求）
        login_url = "https://www.codebuddy.ai/auth/realms/copilot/login-actions/authenticate?session_code=xxjnB7YjKIl_ajufRD5EqDl_yPvKhdn94um5DLP2DUo&execution=fddd3124-02c5-4e2e-9e11-2849f14b804f&client_id=console&tab_id=6MTzVOJ10oI&client_data=eyJydSI6Imh0dHBzOi8vd3d3LmNvZGVidWRkeS5haS9jb25zb2xlL2FjY291bnRzLy5hcGlzaXgvcmVkaXJlY3QiLCJydCI6ImNvZGUiLCJzdCI6ImFhNzllMDRiOTYzNDBkMTRhZjcwNGZjYWFiYzM5NWZkIn0"
        
        # 请求头（来自提供的fetch请求）
        headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "max-age=0",
            "content-type": "application/x-www-form-urlencoded",
            "priority": "u=0, i",
            "sec-ch-ua": "\"Not;A=Brand\";v=\"99\", \"Microsoft Edge\";v=\"139\", \"Chromium\";v=\"139\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "document",
            "sec-fetch-mode": "navigate",
            "sec-fetch-site": "same-origin",
            "sec-fetch-user": "?1",
            "upgrade-insecure-requests": "1"
        }
        
        # 请求体数据（已URL编码）
        data = "username=154hdgrkk7%40dpmurt.my&password=5gHpr0V%21&credentialId="
        
        # 解码显示实际的用户名和密码
        username = unquote("154hdgrkk7%40dpmurt.my")  # 154hdgrkk7@dpmurt.my
        password = unquote("5gHpr0V%21")              # 5gHpr0V!
        
        print(f"👤 用户名: {username}")
        print(f"🔑 密码: {password}")
        
        try:
            # 发送POST登录请求
            response = self.session.post(
                login_url,
                headers=headers,
                data=data,
                allow_redirects=True,
                timeout=30
            )
            
            print(f"\n📊 响应状态码: {response.status_code}")
            print(f"🔗 最终URL: {response.url}")
            print(f"📏 响应长度: {len(response.text)} 字符")
            
            # 分析响应结果
            return self.analyze_login_response(response)
            
        except requests.exceptions.RequestException as e:
            print(f"❌ 登录请求失败: {e}")
            return False
    
    def analyze_login_response(self, response):
        """分析登录响应结果"""
        print("\n🔍 分析登录响应...")
        
        # 检查状态码
        if response.status_code != 200:
            print(f"❌ HTTP状态码异常: {response.status_code}")
            return False
        
        # 检查URL变化
        final_url = response.url.lower()
        
        if "console" in final_url and "account" in final_url:
            print("✅ 登录成功！已重定向到控制台页面")
            success = True
        elif "error" in final_url or "login" in final_url:
            print("❌ 登录失败，仍在登录页面或错误页面")
            success = False
        elif "redirect" in final_url:
            print("✅ 登录可能成功，正在重定向")
            success = True
        else:
            print("⚠️ 登录状态不确定，需要进一步检查")
            success = None
        
        # 检查响应内容
        response_text = response.text.lower()
        
        # 查找错误指示器
        error_indicators = ["error", "invalid", "incorrect", "failed", "denied"]
        success_indicators = ["dashboard", "console", "welcome", "account"]
        
        has_error = any(indicator in response_text for indicator in error_indicators)
        has_success = any(indicator in response_text for indicator in success_indicators)
        
        if has_error and not has_success:
            print("❌ 响应内容包含错误信息")
            success = False
        elif has_success and not has_error:
            print("✅ 响应内容包含成功指示器")
            success = True
        
        # 显示cookie信息
        self.display_cookies()
        
        return success
    
    def display_cookies(self):
        """显示获取到的cookies"""
        if self.session.cookies:
            print("\n🍪 获取到的Cookies:")
            for cookie in self.session.cookies:
                cookie_value = cookie.value[:50] + "..." if len(cookie.value) > 50 else cookie.value
                print(f"  📌 {cookie.name}: {cookie_value}")
                print(f"     域名: {cookie.domain}, 路径: {cookie.path}")
        else:
            print("\n🍪 未获取到任何cookies")
    
    def test_authenticated_access(self):
        """测试是否能访问需要认证的页面"""
        print("\n🔐 测试认证状态...")
        
        try:
            # 尝试访问控制台页面
            response = self.session.get(f"{self.base_url}/console/accounts", allow_redirects=True)
            
            if response.status_code == 200 and "login" not in response.url.lower():
                print("✅ 能够访问受保护的页面，认证成功")
                return True
            else:
                print("❌ 无法访问受保护的页面，认证失败")
                return False
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 测试认证状态失败: {e}")
            return False
    
    def save_session_info(self):
        """保存session信息到文件"""
        session_info = {
            "cookies": {},
            "headers": dict(self.session.headers)
        }
        
        for cookie in self.session.cookies:
            session_info["cookies"][cookie.name] = {
                "value": cookie.value,
                "domain": cookie.domain,
                "path": cookie.path
            }
        
        try:
            with open("session_info.json", "w", encoding="utf-8") as f:
                json.dump(session_info, f, indent=2, ensure_ascii=False)
            print("💾 Session信息已保存到 session_info.json")
        except Exception as e:
            print(f"❌ 保存session信息失败: {e}")
    
    def run_full_test(self):
        """运行完整的登录测试流程"""
        print("=" * 60)
        print("🎯 CodeBuddy登录测试开始")
        print("=" * 60)
        
        # 设置请求头
        self.setup_headers()
        
        # 步骤1: 获取登录页面
        self.get_login_page()
        
        # 步骤2: 尝试登录
        login_success = self.attempt_direct_login()
        
        # 步骤3: 测试认证状态
        if login_success:
            auth_success = self.test_authenticated_access()
            if auth_success:
                self.save_session_info()
        
        # 总结
        print("\n" + "=" * 60)
        print("📋 测试结果总结")
        print("=" * 60)
        
        if login_success:
            print("✅ 登录请求：成功")
        else:
            print("❌ 登录请求：失败")
        
        print("\n💡 注意事项:")
        print("1. URL中的session_code和execution参数可能会过期")
        print("2. 用户凭据需要是有效的")
        print("3. 可能需要先访问登录页面建立session")
        print("4. 某些安全机制可能阻止自动化登录")

def main():
    """主函数"""
    login_tester = CodeBuddyLogin()
    login_tester.run_full_test()

if __name__ == "__main__":
    main()